from pydub import AudioSegment
from pydub.silence import detect_leading_silence
from pathlib import Path
from argparse import ArgumentParser
from tqdm import tqdm
from loguru import logger

def trim_audio(path: Path, output_path: Path, threshold=-60.0):
    sound = AudioSegment.from_file(path, format="wav")

    start_trim = detect_leading_silence(sound, threshold)
    end_trim = detect_leading_silence(sound.reverse(), threshold)

    duration = len(sound)
    trimmed_sound = sound[start_trim:duration - end_trim]

    trimmed_sound.export(output_path, format="wav")

def trim_audio_folder(path: Path, output_path: Path):
    # create the output directory if it doesn't exist
    output_path.mkdir(parents=True, exist_ok=True)
    logger.info(f'going to trim audio files in {path} to {output_path}')
    for wav_file in tqdm(Path(path).rglob('*.wav')):
        # create sub directory if it doesn't exist
        related_path = wav_file.relative_to(path)
        subdir = output_path / related_path.parent
        subdir.mkdir(parents=True, exist_ok=True)
        trim_audio(wav_file, subdir / wav_file.name)

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('-i', '--input_path', help='input path', required=True)
    parser.add_argument('-o', '--output_path', help='output path', required=True)
    args = vars(parser.parse_args())

    trim_audio_folder(Path(args['input_path']), Path(args['output_path']))